(function ($, window, document, undefined) {
    'use strict';
    $.fn.lancesOperationsInitialize = function (o) {
        var op = {url: !1},
        initialize = true;



        $('.btn-ico').on('click', function () {
            $(this).find('i').toggleClass('i-on');

        });

        $('.bid-click').off('click').on('click', function (e) {
            e.preventDefault();
            $('.bid-click').removeClass('is-active');
            $(this).addClass('is-active');
            var $id = $(this).attr('bid-id'),
                    $painel = $('[data-lote-id="' + $id + '"]'),
                    bidMultiply = $(this).attr('ival');

            if ($painel.data('data') == undefined) {
                $painel.data('data', {lanceAutomatico: 0, increment: 0, bidLimit: 30, countBid: 0});
            }

            $painel.find('.btn-lance-aut').addClass('on');
            $painel.find('.lance-atual-black.yellow-esc').addClass('on-label-autol-ance');

            if ($('[data-lote-id="' + $id + '"] .lance-automatic-box').css('display') == 'none') {
                $('[data-lote-id="' + $id + '"] .lance-automatic-box').slideDown(300);
            }

            var op = $painel.data('data');

            op.countBid += parseInt(bidMultiply, 10);
            if (op.bidLimit != 0 && op.countBid > op.bidLimit) {
                op.countBid -= parseInt(bidMultiply, 10);
                showBoxInfo('Lance automático acima do permitido');
                return;
            }

            if ($('[data-lote-id="' + $id + '"] .lance-automatic-box').css('display') != 'none') {

                var increment = $('[data-lote-id="' + $id + '"] .incremento-price').text();
                increment = increment.replace(/\./gi, '').replace(/\,/gi, '.');
                increment = parseFloat(increment);
                var lance = $('[data-lote-id="' + $id + '"] .label-lance-ganhador').text();
                lance = lance.replace(/\./gi, '').replace(/\,/gi, '.');
                lance = parseFloat(lance);
                var $lanceCalc = lance + (increment * bidMultiply);
                if (op.lanceAutomatico > 0 || op.lanceAutomatico >= lance) {
                    op.lanceAutomatico += (increment * bidMultiply);
                } else {
                    op.lanceAutomatico = $lanceCalc;
                }
                op.increment = increment;
            }

            $('[data-lote-id="' + $id + '"] .lance-automatic-value').text(number_format(op.lanceAutomatico, 2, ',', '.'));


        });

        $('.btn-lance-aut').on('click', function (e) {

            var pattern = /on/gi,
                    $iclass = $(this).attr('class'),
                    $id = $(this).attr('auto-id');
            if (pattern.test($iclass)) {

                $.ajax({
                    url: url_site + 'deleteAutoLance.html',
                    dataType: 'json',
                    data: {
                        'l-id': $id
                    },
                    type: 'post',
                    success: function (data) {
                        if (data.error == false) {
                            $('[close-id="' + $id + '"]').trigger('click');
                        } else {
                            alert(data.message);
                        }
                    }
                })
            }

        });

        $('[resetBids]').off('click').on('click', function (e) {
            e.preventDefault();

            var $id = $(this).attr('close-id');

            $('[data-lote-id="' + $id + '"] .bid-click').removeClass('is-active');
            $('[data-lote-id="' + $id + '"]').find('.btn-lance-aut').removeClass('on');
            $('[data-lote-id="' + $id + '"] .lance-automatic-box').slideUp(500, function () {

                $('[data-lote-id="' + $id + '"] .lance-automatic-value').text('');
            });

            $('[data-lote-id="' + $id + '"]').removeData('data');
            $('[data-lote-id="' + $id + '"] .on-label-autol-ance').removeClass('on-label-autol-ance');

        });


        $('[add-lance-automatic]').off('click.LanceAutomatico').on('click.LanceAutomatico', function (e) {
            e.preventDefault();

            var $u_id = $(this).attr('u-id'),
                    $l_id = $(this).attr('l-id'),
                    $lt_id = $(this).attr('lt-id'),
                    $has_class = $(this).attr('class'),
                    pattern = /HGA/gi;

            $.fancybox({
                type: 'ajax',
                width: 250,
                height: 270,
                scrolling: 'no',
                autoResize: false,
                autoSize: false,
                href: url_site + 'showAutoLance-' + $u_id + '-' + $l_id + '.html',
                afterLoad: function () {
                    setInterval($.fn.initLanceAuto, 100);
                }
            });
        });

        $('[no-lance-user]').on('click', function (e) {
            e.preventDefault();
            showBoxInfo('Esse usuário não tem permissão para realizar essa operação.<br/> Verifique sua situação cadastral.');
        });
        /**
         * Add Lance in lote
         * 
         */
        $('[addLance]').off('click.AddLance').on('click.AddLance', function (e) {
            e.preventDefault();
            addLance(this);

        });



        function addLance(obj) {
            var $id = $(obj).attr('lance-lote-id'),
                    $lid = $(obj).attr('leilao-id'),
                    $painel = $('[data-lote-id="' + $id + '"]'),
                    date_ativo_finish = $(this).attr('data-lance-lote'),
                    $time = $painel.data('_time'),
                    upd = 'no',
                    $seconds = 0,
                    $isActive = $('[data-lote-id="' + $id + '"]').find('.bid-click.is-active'),
                    $autoLanceVal = $isActive.attr('ival') || 0,
                    $autoLance = $painel.data('data') ? $painel.data('data') : false,
                    $buttonlabel = $('[data-lote-id="' + $id + '"] .button-lance-label'),
                    $buttonloading = $('[data-lote-id="' + $id + '"] .loading-button'),
                    $objBlocked = $('[data-lote-id="' + $id + '"] .blocked-lance'),
                    $objBoxValueLanceAuto = $('[data-lote-id="' + $id + '"] .lance-automatic-box');
            $buttonlabel.css('visibility', 'hidden');
            $buttonloading.show();
            // console.log($time.$seconds +':'+(firstSeconds ));
            if ($time != undefined) {

                upd = $time.$seconds < firstSeconds ? 'yes' : 'no';
                $seconds = $time.$seconds;
                updateMinutes -= $seconds;
            }

            /*
             $.onTickerleilao.tickers_stamp[$id] = false;
             if (upd === 'yes') {
             var $mktime = mktime(date('H'), date('i'), date('s'), date('m'), date('d'), date('Y'));
             $.onTickerleilao.tickers_stamp[idLt] = date('Y-m-d H:i:s', $mktime);
             }*/

            if ($.isAjaxLance === 1) {
                $.isAjaxLance = 0;
                $.ajax({
                    url: url_site + 'save-lance.html',
                    type: 'post',
                    dataType: 'json',
                    beforeSend: function () {

                        $('.disabled-lances').show();
                        $.isAjaxLance = 0;
                    },
                    data: {
                        lote_id: $id,
                        updtime: upd,
                        leilao_id: $lid,
                        autoLance: $autoLance,
                        autoLanceVal: $autoLanceVal,
                        end: date_ativo_finish
                    },
                    success: function (data) {
                        $('.disabled-lances').hide();
                        if (data.error) {
                            alert(data.message);
                        }
                    },
                    complete: function () {
                        $.isAjaxLance = 1;
                        $buttonlabel.css('visibility', 'visible');
                        $buttonloading.hide();
                        if ($autoLance) {
                            $objBlocked.removeClass('hide');
                            $objBoxValueLanceAuto.slideUp();

                        }
                    }
                });
            }
        }

    };


    $.fn.initLanceAuto = function () {

        $('[moneyMask]').maskMoney({
            thousands: ".",
            decimal: ",", });

        $('[hasConfirmAutoLance]').off('click.hasConfirmAutoLance').on('click.hasConfirmAutoLance', function (e) {
            e.preventDefault();
            var $val = $('[moneyMask]').val(),
                    $u_id = $(this).attr('u-id'),
                    $l_id = $(this).attr('l-id'),
                    self = this;

            $.ajax({
                'url': url_site + 'home/confirmAutoLance',
                data: {'total': $val, 'u-id': $u_id, 'l-id': $l_id},
                type: 'POST',
                dataType: 'json',
                beforeSend: function () {
                    $(self).attr('disabled', 'disabled');
                },
                complete: function (data) {
                    var obj = $.parseJSON(data.responseText);
                    if (obj.error == false) {
                        // window.location.reload();
                        $('.btn-lance-aut[l-id="' + $l_id + '"]').addClass('on');
                        $('.fancybox-close').trigger('click');
                    }
                    $(self).removeAttr('disabled');
                    // $('.fancybox-close').trigger('click');
                }
            });
        });

        $('[cancelAutoLance]').off('click.hasConfirmAutoLance').on('click.hasConfirmAutoLance', function (e) {
            e.preventDefault();
            var $u_id = $(this).attr('u-id'),
                    $l_id = $(this).attr('l-id'),
                    self = this;

            $.ajax({
                'url': url_site + 'home/cancelAutoLance',
                data: {'u-id': $u_id, 'l-id': $l_id},
                type: 'POST',
                dataType: 'json',
                beforeSend: function () {
                    $(self).attr('disabled', 'disabled');

                },
                complete: function (data) {
                    var obj = $.parseJSON(data.responseText);
                    if (obj.error == false) {

                        $('.fancybox-close').trigger('click');
                        $('.btn-lance-aut[l-id="' + $l_id + '"]').removeClass('on');
                    }
                    $(self).removeAttr('disabled');

                }
            });
        });

    };

    jQuery.fn.watch = function (id, fn) {

        return this.each(function () {

            var self = this;

            var oldVal = self[id];
            $(self).data(
                    'watch_timer',
                    setInterval(function () {
                        if (self[id] !== oldVal) {
                            fn.call(self, id, oldVal, self[id]);
                            oldVal = self[id];
                        }
                    }, 100)
                    );

        });

        return self;
    };

    jQuery.fn.unwatch = function (id) {

        return this.each(function () {
            clearInterval($(this).data('watch_timer'));
        });

    };

})(jQuery, window, document);



(function ($, window, document, undefined) {

    $.fn.animatedBG = function (options) {
        var defaults = {
            colorSet: ['#c21515', '#ffffff'],
            speed: 100
        },
        settings = $.extend({}, defaults, options);

        return this.each(function () {
            var $this = $(this);

            $this.each(function () {
                var $el = $(this),
                        colors = settings.colorSet;

                function shiftColor() {
                    var color = colors.shift();
                    colors.push(color);
                    return color;
                }

                // initial color
                var initColor = shiftColor();
                $el.css('backgroundColor', initColor);
                setInterval(function () {
                    var color = shiftColor();
                    $el.css({backgroundColor: color});
                }, settings.speed);
            });
        });
    };

}(jQuery, window, document));